package com.weishenai.customerassistant.controller.sys;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.weishenai.customerassistant.common.Result;
import com.weishenai.customerassistant.controller.BaseController;
import com.weishenai.customerassistant.entity.sys.SysMenuEntity;
import com.weishenai.customerassistant.entity.sys.SysRoleMenuEntity;
import com.weishenai.customerassistant.entity.sys.SysUserEntity;
import com.weishenai.customerassistant.service.SysMenuService;
import com.weishenai.customerassistant.service.SysRoleMenuService;
import com.weishenai.customerassistant.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author weishenai
 * @since 2021-11-27
 */
@Api(tags = "管理系统 菜单管理")
@Slf4j
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * @Description: 获取当前用户的菜单栏以及权限
     * @Param: [principal]
     * @return: com.weishenai.blog.common.lang.Result
     * @Author: weishenai
     * @Date: 2021/11/28
     */
    @ApiOperation("获取当前用户的菜单栏以及权限")
    @GetMapping("/nav")
    public Result nav(Principal principal) {
        String username = principal.getName();
        SysUserEntity sysUser = sysUserService.getByUsername(username);
        String[] authority = StringUtils.tokenizeToStringArray(
                sysUserService.getUserAuthorityInfo(sysUser.getId()), ",");
        return Result.success(MapUtil.builder()
                .put("nav", sysMenuService.getCurrentUserNav())
                .put("authority", authority).map());
    }

    @ApiOperation("通过id获取菜单信息")
    @ApiImplicitParam(name = "id",value = "菜单id")
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result info(@PathVariable("id") long id) {
        return Result.success(sysMenuService.getById(id));
    }

    @ApiOperation("获取菜单列表")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result list() {
        List<SysMenuEntity> menus =
                sysMenuService.list(Wrappers.lambdaQuery(SysMenuEntity.class)
                        .orderByAsc(SysMenuEntity::getOrdernum));
        return Result.success(menus);
    }

    @ApiOperation("添加或更新菜单")
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result save(@RequestBody SysMenuEntity sysMenu) {
        if (sysMenu.getId()==null ){
            sysMenuService.save(sysMenu);
            return Result.success(sysMenu);
        }
        sysMenuService.updateById(sysMenu);
        // 清除所有与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(sysMenu.getId());
        return Result.success(sysMenu);
    }

    @ApiOperation("根据id删除菜单")
    @ApiImplicitParam(value = "id",name = "菜单id")
    @Transactional
    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result delete(@PathVariable Long id) {
        long count = sysMenuService.count(Wrappers.lambdaQuery(SysMenuEntity.class).eq(SysMenuEntity::getParentId, id));
        if (count > 0) {
            return Result.failed("请先删除子菜单");
        }
        // 先清除所有与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(id);
        sysMenuService.removeById(id);

        // 同步删除
        sysRoleMenuService.remove(Wrappers.lambdaQuery(SysRoleMenuEntity.class).eq(SysRoleMenuEntity::getMenuId, id));
        return Result.success("");
    }
}
